package cn.whdream.datastructure;

public class SparseArrayTest {
	
	public static void main(String[] args) {
		int[][] arr = new int[11][11];
		arr[1][2] = 1;
		arr[2][3] = 2;
		int counter=0;
		System.out.println("原始数组");
		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr.length; j++) {
				int data = arr[i][j];
				System.out.printf("%d\t",data);
				if (data != 0) {
					counter++;
				}
			}
			System.out.println();	
		}
		System.out.println("稀疏数组");
		int[][] sparseArray = new int[counter+1][3];
		sparseArray[0][0] = arr.length;
		sparseArray[0][1] = arr[0].length;
		sparseArray[0][2] = counter;
		int x= 0;
		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr.length; j++ ) {
				int temp = arr[i][j];
				if (temp > 0) {
					x++;
					sparseArray[x][0] = i;
					sparseArray[x][1] = j;
					sparseArray[x][2] = temp;
				}
			
			}
		}
		System.out.println("稀疏数组展示");
		for (int i = 0; i < sparseArray.length; i++) {
			for (int j = 0; j < sparseArray.length; j++) {
				int data = sparseArray[i][j];
				System.out.printf("%d\t",data);
				
			}
			System.out.println();	
		}
		
		System.out.println("恢复数据");
		int _x = sparseArray[0][0];
		int _y = sparseArray[0][1];
		int[][] restore = new int[_x][_y];
		for (int i = 1; i < sparseArray.length; i++) {
				int valueX = sparseArray[i][0];
				int valueY = sparseArray[i][1];
				int value = sparseArray[i][2];
				restore[valueX][valueY] = value;
		}
		System.out.println("恢复数据后的数组");
		for (int i = 0; i < restore.length; i++) {
			for (int j = 0; j < restore.length; j++) {
				int data = restore[i][j];
				System.out.printf("%d\t",data);
				
			}
			System.out.println();	
		}
	}
}
